import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _excluded = ["creatorButtonProps", "deleteIconProps", "copyIconProps", "itemContainerRender", "itemRender", "alwaysShowItemLabel", "prefixCls", "creatorRecord", "action", "actionGuard", "children", "actionRender", "fields", "meta", "field", "index", "formInstance", "originName", "min", "max", "count"];
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { CopyOutlined, DeleteOutlined } from '@ant-design/icons';
import { Spin, Tooltip } from 'antd-v4';
import toArray from "rc-util/es/Children/toArray";
import set from "rc-util/es/utils/set";
import { noteOnce } from "rc-util/es/warning";
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { FormListContext } from '.';
import { useGridHelpers } from '../../helpers';
/** Antd 自带的toArray 不支持方法，所以需要自己搞一个 */

var listToArray = function listToArray(children) {
  if (Array.isArray(children)) {
    return children;
  }

  if (typeof children === 'function') {
    return [children];
  }

  return toArray(children);
};

var ProFormListItem = function ProFormListItem(props) {
  var _formInstance$getFiel2;

  var creatorButtonProps = props.creatorButtonProps,
      deleteIconProps = props.deleteIconProps,
      copyIconProps = props.copyIconProps,
      itemContainerRender = props.itemContainerRender,
      itemRender = props.itemRender,
      alwaysShowItemLabel = props.alwaysShowItemLabel,
      prefixCls = props.prefixCls,
      creatorRecord = props.creatorRecord,
      action = props.action,
      actionGuard = props.actionGuard,
      children = props.children,
      actionRender = props.actionRender,
      fields = props.fields,
      meta = props.meta,
      field = props.field,
      index = props.index,
      formInstance = props.formInstance,
      originName = props.originName,
      min = props.min,
      max = props.max,
      count = props.count,
      rest = _objectWithoutProperties(props, _excluded);

  var listContext = useContext(FormListContext);
  var unmountedRef = useRef(false);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      loadingRemove = _useState2[0],
      setLoadingRemove = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      loadingCopy = _useState4[0],
      setLoadingCopy = _useState4[1];

  useEffect(function () {
    return function () {
      unmountedRef.current = true;
    };
  }, []);

  var getCurrentRowData = function getCurrentRowData() {
    return formInstance.getFieldValue([listContext.listName, originName, index === null || index === void 0 ? void 0 : index.toString()].flat(1).filter(function (item) {
      return item !== null && item !== undefined;
    }));
  };

  var formListAction = {
    getCurrentRowData: getCurrentRowData,
    setCurrentRowData: function setCurrentRowData(data) {
      var _formInstance$getFiel;

      var oldTableDate = (formInstance === null || formInstance === void 0 ? void 0 : (_formInstance$getFiel = formInstance.getFieldsValue) === null || _formInstance$getFiel === void 0 ? void 0 : _formInstance$getFiel.call(formInstance)) || {};
      var rowKeyName = [listContext.listName, originName, index === null || index === void 0 ? void 0 : index.toString()].flat(1).filter(Boolean);
      var updateValues = set(oldTableDate, rowKeyName, _objectSpread(_objectSpread({}, getCurrentRowData()), data || {}));
      return formInstance.setFieldsValue(updateValues);
    }
  };
  var childrenArray = listToArray(children).map(function (childrenItem) {
    if (typeof childrenItem === 'function') {
      return childrenItem === null || childrenItem === void 0 ? void 0 : childrenItem(field, index, _objectSpread(_objectSpread({}, action), formListAction), count);
    }

    return childrenItem;
  }).map(function (childrenItem, itemIndex) {
    if ( /*#__PURE__*/React.isValidElement(childrenItem)) {
      var _childrenItem$props, _childrenItem$type, _childrenItem$props2;

      var hasKey = !!childrenItem.key || !!(childrenItem === null || childrenItem === void 0 ? void 0 : (_childrenItem$props = childrenItem.props) === null || _childrenItem$props === void 0 ? void 0 : _childrenItem$props.name) || (childrenItem === null || childrenItem === void 0 ? void 0 : (_childrenItem$type = childrenItem.type) === null || _childrenItem$type === void 0 ? void 0 : _childrenItem$type.toString()) === 'Symbol(react.fragment)';
      noteOnce(hasKey, 'ProFormList 的 children 不设置 key 可能导致更新不及时或者修改不生效的问题，请设置 key。');
      noteOnce(hasKey, "ProFormList's children do not set the key may cause updates not to be timely or the modification does not take effect, please set the key.");
      return /*#__PURE__*/React.cloneElement(childrenItem, _objectSpread({
        key: childrenItem.key || (childrenItem === null || childrenItem === void 0 ? void 0 : (_childrenItem$props2 = childrenItem.props) === null || _childrenItem$props2 === void 0 ? void 0 : _childrenItem$props2.name) || itemIndex
      }, childrenItem === null || childrenItem === void 0 ? void 0 : childrenItem.props));
    }

    return childrenItem;
  });
  var copyIcon = useMemo(function () {
    /** 复制按钮的配置 */
    if (copyIconProps === false || max === count) return null;
    var _copyIconProps$Icon = copyIconProps.Icon,
        Icon = _copyIconProps$Icon === void 0 ? CopyOutlined : _copyIconProps$Icon,
        tooltipText = copyIconProps.tooltipText;
    return _jsx(Tooltip, {
      title: tooltipText,
      children: _jsx(Spin, {
        spinning: loadingCopy,
        children: _jsx(Icon, {
          className: "".concat(prefixCls, "-action-icon action-copy"),
          onClick: function () {
            var _onClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
              return _regeneratorRuntime().wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      setLoadingCopy(true);
                      _context.next = 3;
                      return action.add(formInstance === null || formInstance === void 0 ? void 0 : formInstance.getFieldValue([listContext.listName, rest.name, field.name].filter(function (item) {
                        return item !== undefined;
                      }).flat(1)));

                    case 3:
                      setLoadingCopy(false);

                    case 4:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            }));

            function onClick() {
              return _onClick.apply(this, arguments);
            }

            return onClick;
          }()
        })
      })
    }, "copy");
  }, [copyIconProps, max, count, loadingCopy, prefixCls, action, formInstance, listContext.listName, rest.name, field.name]);
  var deleteIcon = useMemo(function () {
    if (deleteIconProps === false || min === count) return null;
    var _deleteIconProps$Icon = deleteIconProps.Icon,
        Icon = _deleteIconProps$Icon === void 0 ? DeleteOutlined : _deleteIconProps$Icon,
        tooltipText = deleteIconProps.tooltipText;
    return _jsx(Tooltip, {
      title: tooltipText,
      children: _jsx(Spin, {
        spinning: loadingRemove,
        children: _jsx(Icon, {
          className: "".concat(prefixCls, "-action-icon action-remove"),
          onClick: function () {
            var _onClick2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
              return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                while (1) {
                  switch (_context2.prev = _context2.next) {
                    case 0:
                      setLoadingRemove(true);
                      _context2.next = 3;
                      return action.remove(field.name);

                    case 3:
                      if (!unmountedRef.current) {
                        setLoadingRemove(false);
                      }

                    case 4:
                    case "end":
                      return _context2.stop();
                  }
                }
              }, _callee2);
            }));

            function onClick() {
              return _onClick2.apply(this, arguments);
            }

            return onClick;
          }()
        })
      })
    }, "delete");
  }, [deleteIconProps, min, count, loadingRemove, prefixCls, setLoadingRemove, action, field.name]);
  var defaultActionDom = useMemo(function () {
    return [copyIcon, deleteIcon].filter(function (item) {
      return item !== null && item !== undefined;
    });
  }, [copyIcon, deleteIcon]);
  var actions = (actionRender === null || actionRender === void 0 ? void 0 : actionRender(field, action, defaultActionDom, count)) || defaultActionDom;
  var dom = actions.length > 0 ? _jsx("div", {
    className: "".concat(prefixCls, "-action"),
    children: actions
  }) : null;
  var options = {
    name: rest.name,
    field: field,
    index: index,
    record: formInstance === null || formInstance === void 0 ? void 0 : (_formInstance$getFiel2 = formInstance.getFieldValue) === null || _formInstance$getFiel2 === void 0 ? void 0 : _formInstance$getFiel2.call(formInstance, [listContext.listName, rest.name, field.name].filter(function (item) {
      return item !== undefined;
    }).flat(1)),
    fields: fields,
    operation: action,
    meta: meta
  };

  var _useGridHelpers = useGridHelpers(),
      grid = _useGridHelpers.grid;

  var itemContainer = (itemContainerRender === null || itemContainerRender === void 0 ? void 0 : itemContainerRender(childrenArray, options)) || childrenArray;

  var contentDom = (itemRender === null || itemRender === void 0 ? void 0 : itemRender({
    listDom: _jsx("div", {
      className: "".concat(prefixCls, "-container"),
      style: {
        width: grid ? '100%' : undefined
      },
      children: itemContainer
    }),
    action: dom
  }, options)) || _jsxs("div", {
    className: "".concat(prefixCls, "-item ").concat(alwaysShowItemLabel ? "".concat(prefixCls, "-item-show-label") : ''),
    style: {
      display: 'flex',
      alignItems: 'flex-end'
    },
    children: [_jsx("div", {
      className: "".concat(prefixCls, "-container"),
      style: {
        width: grid ? '100%' : undefined
      },
      children: itemContainer
    }), dom]
  });

  return _jsx(FormListContext.Provider, {
    value: _objectSpread(_objectSpread({}, field), {}, {
      listName: [listContext.listName, originName, field.name].filter(function (item) {
        return item !== undefined;
      }).flat(1)
    }),
    children: contentDom
  });
};

export { ProFormListItem };